package com.stylefeng.guns.biz.api.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.biz.api.model.UserSign;
import com.stylefeng.guns.biz.api.service.IUserSignService;
import com.stylefeng.guns.biz.app.model.TAppList;
import com.stylefeng.guns.biz.app.service.ITAppListService;
import com.stylefeng.guns.biz.wxchat.model.TWechatUser;
import com.stylefeng.guns.biz.wxchat.service.ITWechatUserService;
import com.stylefeng.guns.core.redis.RedisService;
import com.stylefeng.guns.core.result.BaseResultVo;
import com.stylefeng.guns.core.result.JsonReturnHelper;
import com.stylefeng.guns.core.util.HttpURLConnUtils;

/**
 * 小程序登录
 */
@Controller
@RequestMapping("/api/mini")
public class MiniLoginController {

    @Autowired
    private RedisService redisService;

    @Autowired
    private ITWechatUserService iTWechatUserService;

    @Autowired
    private ITAppListService tAppListService;

    @Autowired
    private IUserSignService iUserSignService;

    /**
     * 根据code获取用户信息
     * @return
     */
    @RequestMapping("/getUserInfo")
    @ResponseBody
    public BaseResultVo getUserInfo(String openId){

        Map<String, Object> resultMap = new HashMap<>();
        try {

            Map<String, Object> reqParam = new HashMap<String, Object>();
            reqParam.put("open_id", openId);
            List<TWechatUser> tWechatUsers = iTWechatUserService.selectByMap(reqParam);


            TWechatUser tWechatUser = null;
            if (CollectionUtils.isNotEmpty(tWechatUsers)) {
                tWechatUser = tWechatUsers.get(0);
                resultMap.put("userInfo",tWechatUser);
            }

            //查询用户签到状态
            if (tWechatUser.getId() != null) {
                int count = iUserSignService.selectSignByUserId(tWechatUser.getId());
                if (count != 0) {
                    resultMap.put("signStatus", true);
                } else {
                    resultMap.put("signStatus", false);
                }
            } else {
                resultMap.put("signStatus", false);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return JsonReturnHelper.getSuccessWithData(resultMap);
    }


    /**
     * 用户登录
     * @return
     */
    @RequestMapping("/userLogin")
    @ResponseBody
    public BaseResultVo userLogin(String code,TWechatUser tWechatUser){

        Map<String, Object> resultMap = new HashMap<>();
        try {

            if (StringUtils.isBlank(tWechatUser.getOpenId())) {
                Map<String, Object> appParamMap = new HashMap<String, Object>();
                appParamMap.put("app_id", tWechatUser.getAppId());
                List<TAppList> tAppLists = tAppListService.selectByMap(appParamMap);
                if (CollectionUtils.isNotEmpty(tAppLists)) {

                    TAppList tAppList = tAppLists.get(0);
                    String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+tAppList.getAppId()+"&secret="+tAppList.getAppSecret()+"&js_code="+code+"&grant_type=authorization_code";
                    String result = HttpURLConnUtils.httpGET(url);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    tWechatUser.setOpenId(jsonObject.get("openid") == null ? "" : jsonObject.get("openid").toString());
                }
            }

            int count = iTWechatUserService.insertOrUpdateByOpenId(tWechatUser);

            if (count != 0) {
                HashMap<String, Object> objectHashMap = new HashMap<>();
                objectHashMap.put("open_id", tWechatUser.getOpenId());
                List<TWechatUser> tWechatUsers = iTWechatUserService.selectByMap(objectHashMap);

                resultMap.put("loginStatus", true);
                resultMap.put("userInfo", tWechatUsers.get(0));
            } else {
                resultMap.put("loginStatus", false);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return JsonReturnHelper.getSuccessWithData(resultMap);
    }

    /**
     * 用户签到
     * @return
     */
    @RequestMapping("/signEveryDate")
    @ResponseBody
    public BaseResultVo signEveryDate(Integer userId ){

        Map<String, Object> resultMap = new HashMap<>();
        try {

            int count = iUserSignService.selectSignByUserId(userId);
            if (count == 0 && userId != null) {
                UserSign userSign = new UserSign();
                userSign.setUserId(userId);
                userSign.setCreateTime(new Date());
                iUserSignService.insert(userSign);

                //增加金额
                TWechatUser tWechatUser = new TWechatUser();
                tWechatUser.setId(userId);
                tWechatUser.setGoldCoin(100);
                iTWechatUserService.updateGoldCoin(tWechatUser);
            }

            resultMap.put("signStatus",true);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return JsonReturnHelper.getSuccessWithData(resultMap);
    }


}
